package com.cloud.idempotent;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloud.common.constants.GlobalConstants;
import com.cloud.common.domain.Result;
import com.cloud.exception.CustomException;
import com.cloud.service.RedisService;
import com.cloud.utils.ServletUtils;
import com.cloud.utils.SpringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复提交
 *
 * @author yzj
 */
@Aspect
public class PostSubmitAspect {

    private static final ThreadLocal<String> KEY_CACHE = new ThreadLocal<>();

    @Before("@annotation(postSubmit)")
    public void doBefore(JoinPoint point, PostSubmit postSubmit) {
        if (postSubmit.interval() < 1) {
            throw new CustomException("重复提交间隔时间不能小于1秒");
        }
        HttpServletRequest request = ServletUtils.getRequest();
        // 请求地址(作为存放cache的key值)
        String url = request.getRequestURI();
        // 请求参数(作为存放cache的value值)
        String nowParams = argsArrayToString(point.getArgs());
        // 唯一值(没有消息头则使用请求地址)
        String submitKey = request.getHeader(GlobalConstants.tokenHeader);
        submitKey = SecureUtil.md5(submitKey + ":" + nowParams);
        // 唯一标识(指定key + url + 消息头)
        String cacheRepeatKey = GlobalConstants.repeatSubmit + url + submitKey;
        String object = SpringUtils.getBean(RedisService.class).get(cacheRepeatKey);
        if (object == null) {
            SpringUtils.getBean(RedisService.class).set(cacheRepeatKey, 0, postSubmit.interval(), TimeUnit.MINUTES);
            KEY_CACHE.set(cacheRepeatKey);
        } else {
            throw new CustomException(postSubmit.message());
        }
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(postSubmit)", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, PostSubmit postSubmit, Object result) {
        if (result instanceof Result) {
            try {
                Result<?> data = (Result<?>) result;
                // 成功则不删除redis数据,保证在有效时间内无法重复提交
                if (data.getCode() == Result.SUCCESS) {
                    return;
                }
                SpringUtils.getBean(RedisService.class).del(KEY_CACHE.get());
            } finally {
                KEY_CACHE.remove();
            }
        }
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(postSubmit)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, PostSubmit postSubmit, Exception e) {
        SpringUtils.getBean(RedisService.class).del(KEY_CACHE.get());
        KEY_CACHE.remove();
    }

    // 请求参数拼装
    private String argsArrayToString(Object[] params) {
        StringBuilder builder = new StringBuilder();
        if (params != null && params.length > 0) {
            for (Object o : params) {
                if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        builder.append(JSONObject.toJSONString(o)).append(" ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return builder.toString();
    }

    /**
     * 判断是否需要过滤的对象
     *
     * @param o 对象信息
     * @return 如果是需要过滤的对象, 则返回true;否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest
                || o instanceof HttpServletResponse || o instanceof BindingResult;
    }

}
